package Export;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;

import javax.swing.JFileChooser;

import DataModel.Feature;
import DataModel.FeatureHolder;
import Viewer.FileChooserX;

/**
 * This class is for the export of a gff3 file.<br>
 * <a href="http://genome.ucsc.edu/FAQ/FAQformat.html#format3">http://genome.ucsc.edu/FAQ/FAQformat.html#format3</a>
 * 
 * @author Stefan Lorenz<br>
 * <br>26.11.2012
 */
public class ExportGff3 {

    /**
     * List of {@link Feature}s to export
     */
    private ArrayList<Feature> list;
    
    /**
     * Filechooser
     */
    private FileChooserX chooserX;

    /**
     * Contructor of the gff3 exporter
     * @param list list with features to export
     * @param chooserX filechooser
     */
    public ExportGff3(FeatureHolder list, FileChooserX chooserX) {
	this.chooserX = chooserX;
	this.list = list;
	try {
	    exportGff3();
	} catch (IOException e) {
	    e.printStackTrace();
	}
    }

    /**
     * Exports the gff3
     * @throws IOException
     */
    private void exportGff3() throws IOException {
	if (this.chooserX.showSaveDialog(null) == JFileChooser.APPROVE_OPTION) {
	    File file = this.chooserX.getSelectedFile();
	    if (!(file.getName().endsWith(".gff3") || file.getName().endsWith(".gff")))
		file = new File(file.getAbsolutePath() + ".gff3");

	    BufferedWriter writer = new BufferedWriter(new FileWriter(file));

	    for (int i = 0; i < this.list.size(); i++) {
		writeGff(writer, this.list.get(i));
	    }
	    writer.flush();
	    writer.close();
	}
    }

    /**
     * Writes {@link Feature} in gff3 format
     * @param writer writer to write
     * @param f feature to export
     * @throws IOException
     */
    private void writeGff(BufferedWriter writer, Feature f) throws IOException {
	String phase = ".";
	for (int i = 0; i < f.getListOfPositions().size(); i++) {
	    writer.write(f.getName() + "\t" + f.getLocus() + "\t" + f.getType() + "\t" + f.getListOfPositions().get(i).getStart() + "\t" + f.getListOfPositions().get(i).getStop() + "\t");
	    writer.write(String.valueOf(f.getScore()));
	    phase = ".";
	    if(f.getType().equals("CDS"))
		 phase = String.valueOf(f.getListOfPositions().get(i).getStart() % 3);
	    
	    writer.write("\t" + f.getStrand() + "\t"+phase+"\t.");
	    writer.newLine();
	    writer.flush();
	}
    }
}
